﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tornado.Properties;
using System.IO;
using System.Management;
using System.Security.Cryptography;
using System.Net;
using Tornado.lib.CsHTTPServer;
namespace Tornado
{
    public partial class frmMain : Form
    {
        MainProcesser processer = new MainProcesser();
        CsHTTPServer fileServer = null;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            loadSetting();

            string hostName = Dns.GetHostName();
            IPAddress[] ipa = Dns.GetHostAddresses(hostName);
            foreach (IPAddress ip in ipa)
            {
                if (ip.ToString().StartsWith("10.") || ip.ToString().StartsWith("192."))
                {
                    cbbxIp.Items.Add(ip);
                    cbbxIp.SelectedItem = ip;
                }
            }
        }

        private void loadSetting()
        {
            tbxHostPassword.Text = Settings.Default.HostPassword;
            tbxGuestPassword.Text = Settings.Default.GuestPassword;
            cbxAutoRandomHostPassword.Checked = Settings.Default.AutoRandomHostPassword;
            cbxAutoRandomGuestPassword.Checked = Settings.Default.AutoRandomGuestPassword;
            txtFilePath.Text = Settings.Default.PresentationFiles;
            if (cbxAutoRandomGuestPassword.Checked)
            {
                btnRandomGuestPassword.PerformClick();
            }
            if (cbxAutoRandomHostPassword.Checked)
            {
                btnRandomHostPassword.PerformClick();
            }
             string HostRoleArr = Settings.Default.HostRoles;
             string GuestRoleArr = Settings.Default.GuestRoles;
             foreach (SignalCodes c in Enum.GetValues(typeof(SignalCodes)))
             {
                 int id = clbxHostRole.Items.Add(c);
                 if (HostRoleArr.Contains( ((byte)c).ToString()) )
                 {
                     clbxHostRole.SetItemChecked(id, true);
                 }
                 id = clbxGuestRole.Items.Add(c);
                 if (GuestRoleArr.Contains(((byte)c).ToString()))
                 {
                     clbxGuestRole.SetItemChecked(id, true);
                 }
             }
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (processer.isReceiveRunning)
            {
                processer.Stop();
                btnStartStop.Text = "&Start";
                gbxAccessPassword.Enabled = true;
                gbxAccessRoles.Enabled = true;
                tbxGuestPassword.UseSystemPasswordChar = false;
                tbxHostPassword.UseSystemPasswordChar = false;
            }
            else
            {
                //set password
                string s = tbxHostPassword.Text.TrimStart('0');
                if (s.Length == 0)
                    s = "0";
                if (s != tbxHostPassword.Text)
                    tbxHostPassword.Text = s;
                Config.HostPassword = short.Parse(tbxHostPassword.Text);
                Settings.Default.HostPassword = tbxHostPassword.Text;

                s = tbxGuestPassword.Text.TrimStart('0');
                if (s.Length == 0)
                    s = "0";
                if (s != tbxGuestPassword.Text)
                    tbxGuestPassword.Text = s;
                Config.GuestPassword = short.Parse(tbxGuestPassword.Text);
                Settings.Default.GuestPassword = tbxGuestPassword.Text;
                //end set password

                processer.Run();
                btnStartStop.Text = "S&top";
                gbxAccessPassword.Enabled = false;
                gbxAccessRoles.Enabled = false;
                tbxGuestPassword.UseSystemPasswordChar = true;
                tbxHostPassword.UseSystemPasswordChar = true;
                Settings.Default.Save();
                Config.load();
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (processer.isReceiveRunning)
            {
                processer.Stop();
            }
            if ((fileServer != null) && fileServer.IsAlive)
            {
                fileServer.Stop();
            }
            Settings.Default.Save();
        }

        private void cbxAutoRandomHostPassword_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.AutoRandomHostPassword = cbxAutoRandomHostPassword.Checked;
        }

        private void cbxAutoRandomGuestPassword_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.AutoRandomGuestPassword = cbxAutoRandomGuestPassword.Checked;
        }

        private void btnRandomHostPassword_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int p = r.Next(9999);
            tbxHostPassword.Text = p.ToString();
        }

        private void btnRandomGuestPassword_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int p = r.Next(9999);
            tbxGuestPassword.Text = p.ToString();
        }

        private void tbxHostPassword_Leave(object sender, EventArgs e)
        {
            Settings.Default.HostPassword = tbxHostPassword.Text;
        }

        private void tbxGuestPassword_Leave(object sender, EventArgs e)
        {
            Settings.Default.GuestPassword = tbxGuestPassword.Text;
        }


        private void clbxHostRole_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            string sCheck = "";
            for (int i = 0; i < clbxHostRole.Items.Count; i++)
            {
                if ((i != e.Index && clbxHostRole.GetItemChecked(i)) ||
                    (i == e.Index && e.NewValue == CheckState.Checked))
                {
                    sCheck += ((byte)((SignalCodes)(clbxHostRole.Items[i]))).ToString() + ',';
                }
            }
            sCheck.TrimEnd(',');
            Settings.Default.HostRoles = sCheck;
            Settings.Default.Save();
        }

        private void clbxGuestRole_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            string sCheck = "";
            for (int i = 0; i < clbxGuestRole.Items.Count; i++)
            {
                if ((i != e.Index && clbxGuestRole.GetItemChecked(i)) ||
                    (i == e.Index && e.NewValue == CheckState.Checked))
                {
                    sCheck += ((byte)((SignalCodes)(clbxGuestRole.Items[i]))).ToString() + ',';
                }
            }
            sCheck.TrimEnd(',');
            Settings.Default.GuestRoles = sCheck;
            Settings.Default.Save();
        }

        //Too much memory
        bool isPowerPointRunning;
        bool isOpenPresentationFile;
        private void tmrCheckPowerpoint_Tick(object sender, EventArgs e)
        {
            isPowerPointRunning = WinProcess.isPowerpointRunning(); // for this
            isOpenPresentationFile = WinProcess.isOpenFile();// and for this
            if (processer.isReceiveRunning)
            {
                if (isPowerPointRunning)
                {
                    if (!isOpenPresentationFile)
                    {
                        btnStartStop.PerformClick(); //stop server
                        lblStatus.Text = "Do not close powerpoint while presentation fime.";
                        btnStartStop.Enabled = false;
                    }
                }
                else
                {
                    btnStartStop.PerformClick(); //stop server
                    lblStatus.Text = "Powerpoint is not running, you must start it first.";
                    btnStartStop.Enabled = false;
                }
            }
            else
            {
                if (isPowerPointRunning)
                {
                    if (isOpenPresentationFile && !btnStartStop.Enabled)
                    {
                        btnStartStop.Enabled = true;
                        lblStatus.Text = "You can start your presentation now.";
                    }
                    else if (!isOpenPresentationFile && btnStartStop.Enabled)
                    {
                        lblStatus.Text = "You must open your presentation file.";
                        btnStartStop.Enabled = false;
                        MessageBox.Show("Open file ");
                    }
                }
                else if (!isPowerPointRunning && btnStartStop.Enabled)
                {
                    lblStatus.Text = "Powerpoint is not running, run powerpoint to start your presentation.";
                    btnStartStop.Enabled = false;
                }
            }
        }

        private void txtFilePath_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void txtFilePath_DragDrop(object sender, DragEventArgs e)
        {
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            if (FileList.Length > 0)
            {
                FileAttributes attr = File.GetAttributes(FileList[0]);
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    txtFilePath.Text = FileList[0];
                    Settings.Default.PresentationFiles = FileList[0];
                }
            }
        }

        private void txtFilePath_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnStartFileServer_Click(object sender, EventArgs e)
        {
            if (txtFilePath.Text.Length == 0)
            {
                MessageBox.Show("You have to drag and drop a presenstation file into above square");
            }
            else
            {
                if ((fileServer!= null) && fileServer.IsAlive)
                {
                    fileServer.Stop();
                    btnStartFileServer.Text = "Start file server";
                }
                else
                {
                    fileServer = new MyServer(8081, txtFilePath.Text);
                    fileServer.Start();
                    btnStartFileServer.Text = "Stop file server";
                }
            }
        }
    }
}
